import {request} from '../../utils/http'

Page({
  data: {
    product: {},
    stageList: [],
    hasMore: false,
    isExpand: false,
    max: 6,
    member: {
      id: '',
      mobile: '',
      name: '',
      token: ''
    },
    storeId: 0,
    order: {},
    invite_code:'',
    price:'',
    remark:'',
    product_id:'',
    hasSign:false
  },
  onLoad(query) {
    // 页面加载
    
    this.setData({
      storeId: query.store_id,
      remark: query.remark,
      name:query.name,
      id:query.id,
      price:query.price,
      cert_no:query.cert_no,
      invite_code:query.invite_code,
      stage: query.stage,
      stageType:query.stageType,
      product_id:query.product_id
    },() => {
      this.fetch(query.id)

    })
  },
  onReady() {
    // 页面加载完成
  },
  onShow() {
    // 页面显示
    my.getStorage({
      key: 'userInfo',
      success: (res) => {
        console.log(res)
        if (res.data) {
          this.setData({
            member: res.data,
          })
        }
      }
    });
  },
  onHide() {
    // 页面隐藏
  },
  onUnload() {
    // 页面被关闭
  },
  onTitleClick() {
    // 标题被点击
  },
  onPullDownRefresh() {
    // 页面被下拉
  },
  onReachBottom() {
    // 页面被拉到底部
  },
  onShareAppMessage() {
    // 返回自定义分享信息
    return {
      // title: '微蓝辅导',
      // desc: '微蓝辅导',
      path: 'pages/index/index',
    };
  },
  fetch(id) {
    let params = {
      store_id:this.data.storeId
    }
    if (this.data.price) {
      params['price'] = this.data.price
    }
   
    if (this.data.stageType == 1 || this.data.stageType == 2) {
      params['user_total_stage'] = this.data.stage
    }

    request('/order/preview/' + id, 'get',params).then(res => {
      if (res.code == 200) {
        let product = res.data.product;
        my.setNavigationBar({
          title:'商品下单',
        })
        // if (product.pay_method == 3) {
        
        // } else{
        //   my.setNavigationBar({
        //     title:'先享后付',
        //   })
        // }


        this.setData({
          product: product,
          stageList: res.data.stageList,
          hasMore: res.data.stageList.length > this.data.max ? true : false
        })
      }
     
    })
  },
  handleExpand() {
    this.setData({
      isExpand: true
    })
  },
  handleReduce() {
    this.setData({
      isExpand: false
    })
  },
  onGetAuthorize(res) {
    console.log(111111);
  },

   /**
  *	初始化数据 - 宿主传参
  */




submit() {
    this.createOrder()
},
getOrderStatus(order_id){
    request('/order/' + order_id, 'get', {queryStatus:1}).then(res => {
      if (res.code == 200) {
        my.redirectTo({
          url: `/pages/pay-result/pay-result?id=${order_id}&status=${res.data.status}`
        })
      }
    })
},
schemeToParams(scheme) {
  console.log(scheme)
  if (!scheme.startsWith('alipays:')) {
    return { message: '! 非 alipays: 开头' };
  }
  var params = {};
  var parseQuery = (str) => {
    return str.replace(/^.*?\?/, '').split('&').map(s => {
      var p = s.includes('=') ? s.indexOf('=') : s.length;
      return [s.slice(0, p), s.slice(p + 1)].map(decodeURIComponent);
    });
  };
  for (var [k, v] of parseQuery(scheme)) {
    if (k == 'appId') {
      if (v.length != 16) {
        return { message: `! 非 16 位 appId '${v}'` };
      }
    } else if (k == 'page') {
      k = 'path';
    } else if (k == 'query') {
      var o = {};
      for (var [x, y] of parseQuery(v)) {
        o[x] = y;
      }
      v = o;
    } else {
      // return { message: `! 不支持参数 '${k}' ` };
    }
    params[k] = v;
  }
  return params;
},
  
  createOrder(){
    let self = this;

    let params = {
      product_id: this.data.product_id, 
      name: this.data.name,
      price: this.data.price,
      remark: this.data.remark,
      cert_no: this.data.cert_no,
      invite_code:this.data.invite_code,
      store_id: this.data.storeId
    }

    if (this.data.stageType == 1 || this.data.stageType == 2) {
      params['user_total_stage'] = this.data.stage
    }
    request('/order/create', 'post', params).then(res => {
        if (res.code == 200) {
          let url = res.data.contract_signurl || '';
          // let url = res.data.sign_info.miniAppUrl || '';
          
          let params = this.schemeToParams(url)
          console.log(params, url)

          this.setData({
            hasSign:true,
            order_id:res.data.id
          })
          if (!params.message) {
            my.navigateToMiniProgram({
              ...params,
              fail: (res) => my.alert({ title: '跳转小程序失败', content: JSON.stringify(res) }),
            });
          }

          
        } else {
          my.showToast({content: res.message});

        }
    
    })
  },

  myOrder(){
    if (!this.data.member.mobile) {
      my.navigateTo({
        url:'/pages/login/login'
      })
      my.showToast({content: '请登录后再操作'});
      return;
    }
    my.navigateTo({ url: '../order/index'})
  },
  view(){
    my.navigateTo({ url: '../orderDetail/index?id=' + this.data.order_id})

  }

});
